<?php

namespace App\Http\Utils\Integral;

use Illuminate\Support\Facades\DB;

/**
 * Class Roles
 * @package App\Http\Utils\Integral
 */
class Roles
{
    /**
     * 订单
     * @var Order
     */
    protected $order;

    /**
     * 幸运积分红包规则
     * @var \Illuminate\Support\Collection
     */
    public $luckRoles;

    /**
     * 单次消费积分红包规则
     * @var \Illuminate\Support\Collection
     */
    public $singleRoles;

    /**
     * 累计消费积分红包规则
     * @var \Illuminate\Support\Collection
     */
    public $cumulativeRoles;

    /**
     * 是否关闭当天的天天红包结算
     * @var bool
     */
    public $closeDayGrant = false;

    /**
     * Task constructor.
     * @param Order $order
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->roles();
        $this->closeDayGrant();
    }

    /**
     * 查询所有规则
     */
    private function roles()
    {
        $this->luckRoles = DB::table('shop_roles')
            ->where([
                'disable' => 'true',
                'type'    => 'luck',
                'shop_id' => $this->order->shop->shopId,
            ])->get([
                'id', 'shop_id', 'luck_consumption', 'luck_day_off', 'luck_count', 'luck_ratio', 'luck_popularize', 'luck_distribution'
            ]);
        $this->singleRoles = DB::table('shop_roles')
            ->where([
                'disable'  => 'true',
                'type'     => 'day',
                'day_type' => 'single',
                'shop_id'  => $this->order->shop->shopId,
            ])->get([
                'id', 'shop_id', 'day_target', 'day_satisfy', 'day_return', 'day_every', 'day_overly'
            ]);
        $this->cumulativeRoles = DB::table('shop_roles')
            ->where([
                'disable'  => 'true',
                'type'     => 'day',
                'day_type' => 'cumulative',
                'shop_id'  => $this->order->shop->shopId,
            ])->get([
                'id', 'shop_id', 'day_target', 'day_satisfy', 'day_return', 'day_every', 'day_overly'
            ]);
    }

    /**
     * 是否关闭当天的天天红包结算
     */
    protected function closeDayGrant()
    {
        foreach ($this->luckRoles as $luckRole) {
            if ($luckRole->luck_day_off == 'true' && $this->closeDayGrant == false) {
                if (count(array_intersect($this->order->popularize, json_decode($luckRole->luck_popularize))) > 0
                    || count(array_intersect($this->order->distribution, json_decode($luckRole->luck_distribution))) > 0) {
                    $this->closeDayGrant = true;
                }
            }
        }
    }
}